<?php
include("../config.php");

header('Content-Type:text/html;charset= UTF-8'); 
date_default_timezone_set('PRC');
set_time_limit(30); 

$conn=mysql_connect ($dbip, $dbuser, $dbpasswd) or die('数据库服务器连接失败：'.mysql_error());
mysql_select_db($dbname, $conn) or die('选择数据库失败');
mysql_query("set names utf8;");
rssreader();
mysql_close($conn);

function rssreader()
{
	global $conn;
	
	$sql="select * from author;";
	$results=mysql_query($sql,$conn);	
	if($results)
	{		
		while($row = mysql_fetch_array($results))
		{	 
			$rss_str="";  
			//打开rss地址，并读取，读取失败则中止
			echo $row['name'].'的全部文章:</br>';
			$author=$row['name'];
			$authorid=$row['id'];
			$lastupdate=$row['update'];
			
			$buff = get_file_curl($row['rssurl']);
			//如果失败，就使用就标记失败次数
			if($buff==false)
			{
				echo 'fail to get rss file !</br>';	
				$sql="update author set failtimes=failtimes+1 where id = $authorid;";
				$result=mysql_query($sql,$conn);
				echo 'update fail info:'.mysql_error().'</br>';	
				continue;
			}				
			$values = xmlrssfile($buff);
			readrssfile($values,$author,$authorid,$lastupdate);			
        }
	}
}

function readrssfile($values,$author,$authorid,$lastupdate)
{
	global $conn;
	//print_r($values);
	$newdate = date("Y-m-d H:i:s",strtotime('0000-00-00 00:00:00'));
	$is_item = 0;$category="";$title="";$link="";$pubdate="";
	$i=0;
	foreach ($values as $val) 
	{  
		$tag = $val["tag"];  
		$type = $val["type"];  
		 
		//标签统一转为小写  
		$tag = strtolower($tag);  
		  
		if ($tag == "item" && $type == "open"){  
			$is_item = 1; 
			continue;
		}
		else if ($tag == "item" && $type == "close") 
		{  
			//构造输出字符串  
			$rss_str = "<a href='".$link."' target=_blank>".$title.$category. "</a><br />"; 
			//比较没有之后插入数据库
			$sql="insert into links(title,link,catnick,authorid,author,pubdate) values('$title','$link','$category',authorid,'$author','$pubdate');";
			$result=mysql_query($sql,$conn);
			echo 'insert links info:'.mysql_error().'</br>';					
			$is_item = 0;$category="";$title="";$link="";$pubdate="";	
			$i++;
		}  
		//仅读取item标签中的内容  
		if($is_item==1)
		{ 
			$value = $val["value"]; 
			if ($tag == "title") {$title = $value;}          
			if ($tag == "link") {$link = $value;}  
			if ($tag == "category") {$category = $value;}
			if ($tag == "pubdate")
			{
				$pubdate = date("Y-m-d H:i:s",strtotime($value));
				echo $pubdate . '</br>';
				echo $newdate . '</br>';
				echo $lastupdate . '</br>';

				//判断时间，如果过早，就直接结束，不向下读取;
				if($pubdate<$lastupdate)
				{
					break;		
				}
				else
				{
					if($pubdate>$newdate)
						$newdate = $pubdate;
						
				}
			}
		}
	}

	if($i>0)
	{
		echo 'end to get rss file !</br>';
		$newdatef = date("Y-m-d H:i:s",strtotime($newdate));
		$sql="update author set author.update='$newdatef' where id = $authorid;";
		$result=mysql_query($sql,$conn);
		echo 'update fail info:'.mysql_error().'</br>';	
	}
}

function xmlrssfile($buff)
{
	$values= '';
	//建立一个 XML 解析器  
	$parser = xml_parser_create();  
	//xml_parser_set_option -- 为指定 XML 解析进行选项设置  
	xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);  
	//xml_parse_into_struct -- 将 XML 数据解析到数组$values中  
	xml_parse_into_struct($parser,$buff,$values,$idx);  
	//xml_parser_free -- 释放指定的 XML 解析器  
	xml_parser_free($parser);
	return $values;
}

function get_file($url)
{
	$buff="";
    set_time_limit(20); // 设置超时时间
    $file = fopen ($url, "r"); // 远程下载文件，二进制模式
    if ($file) 
	{ 	// 如果下载成功
		while ( !feof($file) ) 
		{  
			$buff .= fgets($file,4096);  
		}  
    }
	else
	{
		echo "can not open $url";
		return false;
	}
    if ($file) 
	{
        fclose($file); // 关闭远程文件
    }
    return $buff;
} 

function get_file_contents($url)
{
    return file_get_contents($url);
} 

function get_file_curl($url)
{
	$ch = curl_init();
	$starttime = time();
	$timeout = 20;
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	//在需要用户检测的网页里需要增加下面两行
	//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.”:”.US_PWD);
	$contents = curl_exec($ch);
	curl_close($ch);
	$endtime = time();
	if($endtime-$starttime>=$timeout)
	{
		echo 'php运行超时';
	}
	return $contents;
}

?>